<script setup lang="ts">
import { ref, onMounted } from "vue";
import { useBase64, useFile } from "vue-cache-optimization"; // ./utils vue-cache-optimization
import image from "./../assets/vue.svg";
const { downFile, generateQR, parseQR } = useFile();
console.log(downFile);
console.log(generateQR);
console.log(parseQR);

// 测试 generateQR 函数

// 测试 downFile 函数
const img = ref();
const imgUrl = ref(image);
const imgBase64 = ref("");
const onChange = async (e: any) => {
  const file = e.target.files[0];
  imgUrl.value = URL.createObjectURL(file);
  // imgUrl.value = (await fileConvert(file, "base64")) as string;
};
const getCurrentData = () => {
  imgBase64.value = useBase64(img.value);
};
const downImg = () => {
  downFile(imgBase64.value, "test.png");
};
const clearImg = () => {
  imgBase64.value = "";
  imgUrl.value = image;
};

// 测试二维码生成与解析
const qrtext = ref("123");
const newqrtext = ref("");
const createQRimg = () => {
  generateQR("qr-img", qrtext.value);
};
const getQRtext = async () => {
  newqrtext.value = await parseQR("qr-img");
};
const onChangeQR = async (e: any) => {
  const file = e.target.files[0];
  const qrImg = document.querySelector("#qr-img") as HTMLImageElement;
  qrImg.src = URL.createObjectURL(file);
  // qrImg.src = (await fileConvert(file, "base64")) as string;
};

onMounted(() => {
  createQRimg();
});
</script>

<template>
  <div>
    <p>TestFile</p>
    <h2>测试 downFile 文件下载函数</h2>
    <p>
      <img ref="img" :src="imgUrl" />
      <input type="file" @change="onChange" />
      <button @click="getCurrentData()">获取当前图片的 base64</button>
      <button @click="downImg()">下载图片</button>
      <button @click="clearImg()">清除数据</button>
    </p>
    <p>
      <textarea v-model="imgBase64" id="" cols="100" rows="10"></textarea>
    </p>
    <h2>生成二维码</h2>
    <p>
      <input v-model="qrtext" />
      <button @click="createQRimg()">生成二维码</button>
    </p>
    <p>
      上传二维码
      <input type="file" @change="onChangeQR" />
    </p>
    <p>
      <img id="qr-img" src="" />
    </p>
    <h2>解析二维码</h2>
    <p>
      <button @click="getQRtext()">解析二维码</button>
    </p>
    <p>二维码数据为: {{ newqrtext }}</p>
  </div>
</template>

<style>
.images img {
  width: 200px;
  opacity: 0.2;
}
</style>
